import router,{ DynamicRoutes, constantRoutes, createRouter } from '@/router'
import { permitRoutes } from '@/router/permit_routes'
import { getMenu, setMenu } from '@/util/auth'

/**
 * 
 * @param routes  根据后端菜单得出的侧边菜单
 * @param filterRouters 侧边需要导航的路由
 */
var filterRouters = [];
function filterAsyncRouter (routes) {  
  routes.forEach(item => {
    if(!item.component) {
      if(item.children) {
        filterAsyncRouter(item.children);
      }
    }else {
      filterRouters.push(item);      
    }
  })
  return filterRouters;  
}

/**
 *
 * @param  {Array} userRouter 后台返回的用户权限json
 * @param  {Array} allRouter  前端配置好的所有动态路由的集合
 * @return {Array} realRoutes 过滤后的路由
 */

function recursionRouter(userRouter = [], allRouter = []) {
  var realRoutes = [];
  // console.log(allRouter)
  allRouter.forEach((v, i) => {
    userRouter.forEach((item, index) => {
      let children = item.sub;
      if (item.href == v.href && item.title == v.meta.title) {
        v.id = item.id;
        if (children && children.length > 0) {
          v.children = recursionRouter(item.sub, v.children)
        }   
        realRoutes.push(v);                  
      }
    })
  })
  // console.log(realRoutes)
  return realRoutes
}


const permission = {
  state: {
    // routers: constantRoutes,
    addRoutes: []
  },
  mutations: {
    ['SET_ROUTES'] (state, routers) {      
      state.addRoutes = routers;
    }
  },
  actions: {
    GenerateRoutes ({ commit }, data) {    
      if(getMenu()){
        let menu = JSON.parse(getMenu());
        // console.log(menu)
        if(menu[0].sub && menu[0].sub[0].title == '首页'){
          let obj = menu[0].sub[0]
          menu[0] = obj;
        }
        let routes = recursionRouter(menu, permitRoutes);

        // 可以访问的路由（有权限的路由）
        let realRoutes = filterAsyncRouter(routes);
        
        // 找到待动态添加的路由表，将权限路由添加至动态路由表中
        /**
         * @params DynamicRoutes 动态路由表
         * @params realRoutes 根据菜单的得到的真正可访问路由
         */
        let MainContainer = DynamicRoutes.find(v => v.path === '/');
        let children = MainContainer.children;
        children.push(...realRoutes);

        //生成左侧导航菜单 
        commit('SET_ROUTES', routes);

        /*  初始路由 */
        let initialRoutes = router.options.routes

        // console.log(DynamicRoutes)
        /*  动态添加路由 */
        
        router.match = createRouter(constantRoutes).match;
        // console.log(router.match)

        /**
         * 添加动态路由至路由表
         */
        router.addRoutes(DynamicRoutes)
      }else {
        setMenu([]);
        router.push('/login')
      }
    } 
  }
}

export default permission
